var querySource
var queryVector
var queryDrawLayer
var queryMapLayLoadingLayer
var queryMapResultLayUILayer
var queryDrawInteraction
var queryGeometryFunction
var queryBy = Zondy.Enum.FeatureType.Unknown
var queryOlCurrentFeature
/**
 * @type {Zondy.Object.SFEleArray}
 */
var queryMapGISCurrentFeature
/**
 * @type {Zondy.Object.FeatureSet}
 */
var queryMapGISResultFeatureSet
/**
 * 判断点击查询
 * @returns {boolean}
 */
const queryByPoint = () => queryBy === Zondy.Enum.FeatureType.Pnt
/**
 * 判断拉框查询
 * @returns {boolean}
 */
const queryByRegion = () => queryBy === Zondy.Enum.FeatureType.Reg

/**
 *
 * @param by
 */
function queryVectorLayerBy(by) {
    queryBy = by
    clearLayer()
    querySource = new ol.source.Vector({wrapX: false})
    queryVector = new ol.layer.Vector({
        source: querySource,
        style: new ol.style.Style({
            image: new ol.style.Circle({
                radius: 0
            })
        })
    })
    map.addLayer(queryVector)

    if (queryByPoint()) {
        queryDrawInteraction = new ol.interaction.Draw({
            type: 'Point',
            source: querySource
        })
    }
    else if (queryByRegion()) {
        var maxPoints = 2
        queryGeometryFunction = function (coordinates, geometry) {
            if (!geometry) {
                //多边形
                geometry = new ol.geom.Polygon(null)
            }
            var start = coordinates[0]
            var end = coordinates[1]
            geometry.setCoordinates([
                [start, [start[0], end[1]], end, [end[0], start[1]], start]
            ])
            return geometry
        }
        queryDrawInteraction = new ol.interaction.Draw({
            type: 'LineString',
            source: querySource,
            geometryFunction: queryGeometryFunction,
            maxPoints: maxPoints
        })
    }

    map.addInteraction(queryDrawInteraction)
    queryDrawInteraction.on('drawend', drawControlback)
}

function clearLayer() {
    if (queryDrawLayer)
        map.removeLayer(queryDrawLayer)
}

function drawControlback(feature) {
    clearLayer()
    var queryStruct = new Zondy.Service.QueryFeatureStruct({
        IncludeGeometry: true,
        IncludeAttribute: true,
        IncludeWebGraphic: false,
    })

    var geomObj
    if (queryByRegion()) {
        geomObj = new Zondy.Object.Polygon()
    } else if (queryByPoint()) {
        geomObj = new Zondy.Object.PointForQuery()
        geomObj.nearDis = 0.01
    }

    geomObj.setByOL(feature.feature.values_.geometry)
    //设置查询点的搜索半径

    //指定查询规则
    var rule = new Zondy.Service.QueryFeatureRule({
        //是否将要素的可见性计算在内
        EnableDisplayCondition: false,
        //是否完全包含
        MustInside: false,
        //是否仅比较要素的外包矩形
        CompareRectOnly: false,
        //是否相交
        Intersect: true
    })
    //实例化查询参数对象
    var queryParam = new Zondy.Service.QueryParameter({
        geometry: geomObj,
        resultFormat: "json",
        struct: queryStruct,
        rule: rule
    })
    //设置查询分页号
    queryParam.pageIndex = 0
    //设置查询要素数目
    queryParam.recordNumber = 20
    //实例化地图文档查询服务对象
    var queryService = new Zondy.Service.QueryDocFeature(queryParam, place.name, getLayerNumberFromLayUI(), {
        ip: ip,
        port: port
    })
    useLayer((layer) => {
        queryMapLayLoadingLayer = searchLoadingMsg(layer)
    })
    //执行查询操作，querySuccess为查询回调函数
    queryService.query(querySuccess)
}

/**
 * 成功的回调函数
 * @param {Zondy.Object.FeatureSet} result
 */
function querySuccess(result) {
    console.log(result)

    //停止进度条
    useLayer(layer => {
        layer.close(queryMapLayLoadingLayer)
        layer.min(curLayUILayer)
    })

    var format = new Zondy.Format.PolygonJSON()
    var features
    try {
        features = format.read(result)
    } catch (e) {
        useLayer(layer => {
            layer.msg("无结果")
        })
        return
    }

    /**
     * 表格数据
     * @param {Zondy.Object.FeatureSet}res
     * @returns {string}
     */
    function genStr(res) {
        queryMapGISResultFeatureSet = result
        let colsTitle = []
        let data = []
        if (res.TotalCount > 0) {
            colsTitle = res.AttStruct.FldName.map(it => {
                return {field: it, title: it}
            })
            res.SFEleArray.forEach(it => {
                let single = {}
                it.AttValue.forEach((v, index) => {
                    single[colsTitle[index].field] = v
                })
                data.push(single)
            })
        }
        colsTitle.forEach(it => {
            let l = Math.max((it.field).replace(/[^\x00-\xff]/gi, "--").length,
                (data[0][it.field].toString()).replace(/[^\x00-\xff]/gi, "--").length)
            it.width = 30 + l * 10
        })

        layui.use('table', () => {
            let table = layui.table
            table.on("tool(resTable)", (obj) => {
                console.log(obj)
            })
            table.render({
                elem: "#resTable",
                cols: [colsTitle],
                data: data,
                cellMinWidth: 40
            })
        })
    }

    useLayer(layer => {
        genStr(result)
        queryMapResultLayUILayer = layer.open({
            type: 1,
            title: "查询结果",
            shade: 0,
            area: ["800px", "200px"],
            maxmin: true,
            offset: [
                ($(window).height() - 200),
                -1
            ],
            content: $("#queryByClickResult").html(),
            zIndex: layer.zIndex,
            success: function (o, index) {
                let theTable = getLayerTable(o)
                theTable.headers.on('click', e => {
                    let cur = e.currentTarget
                    console.log(cur.getAttribute("data-field"))
                    console.log(cur.innerText)
                })
                theTable.tds
                    .on('click', (e, a) => {
                        let cur = e.currentTarget
                        console.log(cur.getAttribute("data-field"))
                        layer.msg(cur.innerText)
                        let index = cur.parentNode.getAttribute("data-index")
                        $(o).css("opacity", "0.8")
                        if (result.TotalCount > 0) {
                            let geom = queryMapGISCurrentFeature = result.SFEleArray[index]
                            let bound = queryMapGISCurrentFeature.bound
                            let xmean = (bound.xmax + bound.xmin) / 2
                            let ymean = (bound.ymax + bound.ymin) / 2
                            map.getView().setCenter([xmean, ymean])
                            // queryOlCurrentFeature = {
                            //     AttStruct: result.AttStruct,
                            //     type: geom.ftype,
                            //     id: geom.FID
                            // }
                        }
                    })
            }
        })
    })
    //实例化一个矢量图层Vector作为绘制层
    var drawSource = new ol.source.Vector({
        //是否在地图水平坐标轴上重复
        wrapX: false
    })
    console.log(features)
    drawSource.addFeatures(features)
    queryDrawLayer = new ol.layer.Vector({
        source: drawSource,
        style: new ol.style.Style({
            //填充色
            fill: new ol.style.Fill({
                color: 'rgba(255, 204, 51, 0.5)'
            }),
            //边线样式
            stroke: new ol.style.Stroke({
                color: 'rgba(255,204, 51, 1)',
                width: 1
            })
        })
    })
    map.addLayer(queryDrawLayer)
}